﻿using AutoMapper;
using MediatR;
using SmartProduction.Domain.ProductionOrders;
using SmartProduction.Domain.采购委外订单;
using SmartProduction.ErrorCode;
using SmartProduction.Infarstructrue.Interface;
using SmartProduction.Read.API.Application.Commands.ProductionOrderNoInfoCommand;

namespace SmartProduction.Read.API.Application.CommandHandlers.ProductionOrderNoInfoCommandHandler
{
    /// <summary>
    /// 生产单号显示命令方法
    /// </summary>
    public class ProductionOrderNoInfoQueryCommandHandler : IRequestHandler<ProductionOrderNoInfoQueryCommand, APIPaing<List<ProductionOrderNoInfo>>>
    {
        /// <summary>
        /// AutoMapper
        /// </summary>
        private readonly IMapper mapper;
        /// <summary>
        /// 生产单号命令处理
        /// </summary>
        private readonly IBaseRepository<ProductionOrderNoInfo> productionRepository;
        /// <summary>
        /// 构造
        /// </summary>
        /// <param name="mapper"></param>
        /// <param name="productionRepository"></param>
        public ProductionOrderNoInfoQueryCommandHandler(IMapper mapper, IBaseRepository<ProductionOrderNoInfo> productionRepository)
        {
            this.mapper = mapper;
            this.productionRepository = productionRepository;
        }
        /// <summary>
        /// 生产单号处理方法
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<APIPaing<List<ProductionOrderNoInfo>>> Handle(ProductionOrderNoInfoQueryCommand request, CancellationToken cancellationToken)
        {
            
            APIPaing<List<ProductionOrderNoInfo>> result = new APIPaing<List<ProductionOrderNoInfo>>();
            var list = productionRepository.GetAll().Result;
            result.TotalCount = list.Count();
            result.PageCount = (int)Math.Ceiling((double)result.TotalCount / request.PageSize);
            list = list.OrderByDescending(o => o.ProductionOrderId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize);
            var data = mapper.Map<List<ProductionOrderNoInfo>>(list);
            result.Code = APIEnums.查询成功;
            result.Msg = APIEnums.查询成功.ToString();
            result.data = data;
            return await Task.FromResult(result);
        }
    }
}
